package com.wolfking.jeesite.service;

import com.wolfking.jeesite.entity.SysKvCache;
import com.wolfking.jeesite.mapper.SysKvCacheMapper;
import com.wolfking.jeesite.mybatis.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Service
public class SysKvCacheService extends BaseService<SysKvCache> {

    @Autowired
    private SysKvCacheMapper sysKvCacheMapper;

    public void put(String key, String value, Date expired) {

        SysKvCache sysKvCache = sysKvCacheMapper.selectByKey(key);
        if (Objects.isNull(sysKvCache)) {
            sysKvCache = new SysKvCache();
            sysKvCache.setCacheKey(key);
        }
        sysKvCache.setCacheValue(value);
        sysKvCache.setExpireTime(expired);
        super.saveOrUpdate(sysKvCache);
    }

    public String get(String key) {
        SysKvCache sysKvCache = sysKvCacheMapper.selectByKey(key);
        if (Objects.isNull(sysKvCache) || sysKvCache.getExpireTime().getTime() < System.currentTimeMillis()) {
            return null;
        }
        return sysKvCache.getCacheValue();
    }

    public void delete(String key) {
        sysKvCacheMapper.deleteByKey(key);
    }
}
